#!/usr/bin/env python3
# _*_ coding:utf-8 _*_

from pathlib import Path
from git.repo import Repo
import git


class GitManage(object):
    """
    git 仓库管理
    """

    def __init__(self, repopath, giturl, branchname='master'):
        self.repopath = repopath
        self.giturl = giturl
        self.branchname = branchname
        self.repoinit()

    def repoinit(self):
        path_obj = Path(self.repopath)
        if not path_obj.exists():
            repo_obj = Repo.clone_from(self.giturl, to_path=self.repopath, branch=self.branchname)
        else:
            repo_obj = Repo(self.repopath)
        self.repo = repo_obj

    def pull(self):
        self.repo.git.pull()

    def __repo(self):
        return git.Git(self.repopath)

    def get_branchs(self):
        """
        获取所有branch
        :return: 返回branch列表
        """
        branches = self.repo.remote().refs
        return [item.remote_head for item in branches if item.remote_head not in ['HEAD', ]]

    def get_commits(self, num=10):
        """
        获取格式化的commit
        :param num: 指定获取数量
        :return: 返回commit列表，每个元素为字典
        """
        commit_log = self.repo.git.log('--pretty={"commit":"%h","author":"%an","summary":"%s","date":"%cd"}',
                                       max_count=num,
                                       date='format:%Y-%m-%d %H:%M')
        log_list = commit_log.split("\n")
        return [eval(item) for item in log_list]

    def get_tags(self):
        """
        获取所有tag
        :return:
        """
        return [tag.name for tag in self.repo.tags]

    def change_to_branch(self, branch):
        """
        切换branch
        :param branch:
        """
        self.repo.git.checkout(branch)

    def change_to_commit(self, branch, commit):
        """
        切换commit
        :param branch:
        :param commit:
        :return:
        """
        self.change_to_branch(branch=branch)
        self.repo.git.reset('--hard', commit)

    def change_to_tag(self, tag):
        """
        切换tag
        :param tag:
        :return:
        """
        self.repo.git.checkout(tag)

    def code_diff(self, old, new):
        return self.__repo().diff(old, new, '--name-status')
